package com.xjrsoft.common.runner;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.config.SaTokenConfig;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.module.system.entity.LoginConfig;
import com.xjrsoft.module.system.service.ILoginConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 登录配置获取
 * @Author: tzx
 * @Date: 2022/12/6 14:50
 */
@Component
@AllArgsConstructor
@Slf4j
public class LoginConfigRunner implements CommandLineRunner {


    private ILoginConfigService loginConfigService;
    @Override
    public void run(String... args) {
        loadLoginConfig();
    }

    @Async
    void loadLoginConfig(){
        List<LoginConfig> list = loginConfigService.list();
        if (list.size() == 0){//如果没有，则设置为默认配置,并进行保存
            LoginConfig loginConfig = new LoginConfig();
            loginConfig.setId(1L);
            loginConfig.setMulLogin("0,1");
            loginConfig.setMutualExclusion(YesOrNoEnum.NO.getCode());
            loginConfig.setWithoutLogin(YesOrNoEnum.YES.getCode());
            loginConfig.setPasswordStrategy(YesOrNoEnum.YES.getCode());
            loginConfig.setStrategyMaxNumber(7);
            list.add(loginConfig);
            loginConfigService.save(loginConfig);
        }
        LoginConfig loginConfig = list.get(0);
        SaTokenConfig oldConfig = SaManager.getConfig();
        if (loginConfig.getMutualExclusion() == YesOrNoEnum.NO.getCode()){
            //不开启同端互斥
            oldConfig.setIsConcurrent(true);
        }else {
            //开启同端互斥
            oldConfig.setIsConcurrent(false);
        }
        // 注入到 SaManager 中
        SaManager.setConfig(oldConfig);
    }

}
